<template>
  <div class="box">
    <div class="container">
      <div class="search-box">
        <div class="search-top-box" :style="moreSearchShow?'height:200px;overflow-y:auto':''">
          <div class="search-top-left-box">
            <el-form label-width="100px" ref="div" :inline="true" :model="formSearch" class="demo-form-inline">
              <el-form-item label="关键词">
                <el-input clearable class="form-width" v-model="formSearch.keyword" placeholder=""></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="search-top-right-box">
            <p v-if="showOpne" @click="moreSearch">{{moreSearchShow?'收起':'展开'}}<i
                :class="moreSearchShow?'el-icon-arrow-up':'el-icon-arrow-down'"></i></p>
            <el-button type="primary" @click="onSearch(1)">查询</el-button>
            <el-button type="primary" class="add" icon="el-icon-plus" @click="addBrankFunc">添加品牌</el-button>
          </div>
        </div>
      </div>
      <!-- table -->
      <el-table :header-cell-style="{background:'#FAFBFC',color:'#828A9D',textAlign:'center'}"
        :cell-style="{textAlign:'center',color:'#1B2431'}" :data="tableData" style="width: 100%"
        v-loading="tableLoading">
        <el-table-column prop="id" label="品牌编号" width="110" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="name" label="品牌名称" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="desc" label="品牌备注" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="updated_at" label="更新时间" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit({index:scope.$index, item:scope.row})">修改</el-button>
            <el-button style="margin-left: 10px;" slot="reference" size="mini" type="danger"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination :page-sizes="[10, 30, 100]" class="el-pagination" @current-change="handleCurrentChange"
      :current-page="page" :page-size="num" @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <!-- 添加品牌 -->
    <el-dialog title="添加品牌" :visible.sync="dialogVisible" width="850px" :before-close="handleClose">
      <div class="scroll-view">
        <el-form label-position="left" label-width="70px" :model="formInline" ref="ruleForm" :rules="rules"
          class="demo-form-inline">
          <el-form-item label="品牌" prop="name">
            <el-input class="el-input" v-model="formInline.name" placeholder="品牌名称"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="desc">
            <el-input class="textarea" type="textarea" :rows="2" placeholder="请输入内容" v-model="formInline.desc">
            </el-input>
          </el-form-item>
          <el-form-item label="节点模板">
            <el-button class="add-node" :loading="nodeLoading" @click="getNodesList({type:'node'})">新增节点模版</el-button>
          </el-form-item>
          <div class="template-box" v-loading="nodeLoading">
            <div class="template-item" v-for="(item,index) in templateList" :key="index">
              <i class="el-icon-error" @click="delFunc({index})"></i>
              <div class="scroll-view">
                <div class="template-title flex jb">
                  <div class="flex">
                    {{item.template_name}}
                    <i class="el-icon-edit" @click="openEdit({index})"></i>
                  </div>
                  <div class="flex">
                    <el-tooltip effect="dark" content="添加验收节点" placement="bottom">
                      <i class="el-icon-circle-plus-outline" @click="getNodesList({type:'node',index})"></i>
                    </el-tooltip>
                  </div>
                </div>
                <div class="node-item-box" v-for="(child,childIndex) in item.template_nodes" :key="childIndex">
                  <div class="node-item-title">
                    <div class="checkbox-box">
                      <el-tooltip effect="dark" content="设置进度款节点" placement="bottom">
                        <el-checkbox @change="checkboxChange({index,childIndex})" :value="child.is_payment_review == 1">
                          <span class="title-text">{{child.node_name}}</span>
                        </el-checkbox>
                      </el-tooltip>
                      <i class="el-icon-edit" @click.stop="openEdit({index,childIndex})"></i>
                    </div>
                    <div>
                      <el-tooltip effect="dark" content="添加验收标准" placement="bottom">
                        <i class="el-icon-circle-plus-outline"
                          @click="getNodesList({type:'check',index,childIndex})"></i>
                      </el-tooltip>
                      <i class="el-icon-delete" @click="delFunc({index,childIndex})"></i>
                    </div>
                  </div>
                  <div class="check-box">
                    <el-tag class="tag" v-for="(i,k) in child.children" :key="k">
                      {{i.node_name}}
                      <i class="el-icon-edit" @click="openEdit({index,childIndex,k})"></i>
                      <i class="el-icon-delete" @click="delFunc({index,childIndex,k})"></i>
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitFunc('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 节点模板 -->
    <el-dialog :title="chooseType == 'node'?'添加节点模版':'添加验收标准'" :visible.sync="dialogVisibleTemplate" width="850px"
      :before-close="handleClose">
      <div class="scroll-view">
        <el-form label-position="left" label-width="80px" :model="formTemplate" ref="ruleFormTemplate"
          :rules="rulesTemplate" class="demo-form-inline">
          <el-form-item label="模板名称" prop="name" v-if="chooseType == 'node' && indexOne==undefined">
            <el-input class="el-input" v-model="formTemplate.name" placeholder="模板名称"></el-input>
          </el-form-item>
          <div class="node-box">
            <el-checkbox-group v-model="formTemplate.nodeCheckVal">
              <el-checkbox v-for="(item,index) in nodesList" :key="index" :label="item.node_name" border></el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleTemplate = false">取 消</el-button>
        <el-button type="primary" @click="submitTemplateFunc('ruleFormTemplate')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import brandApi from '@/api/brandApi'
  import nodesApi from '@/api/nodesApi'
  import _tools from '@/utils/_tools'
  export default {
    name: '',
    data() {
      return {
        tableLoading: false,
        rules: {
          name: [{
            required: true,
            message: '请输入品牌名称',
            trigger: 'change'
          }, ],
        },
        rulesTemplate: {
          name: [{
            required: true,
            message: '请输入模板名称',
            trigger: 'change'
          }, ],
        },
        currIndex: 0,
        dialogVisible: false,
        dialogVisibleTemplate: false,
        page: 1,
        tableData: [],
        moreSearchShow: false,
        showOpne: false,
        total: 0,
        num: 10,
        formSearch: {
          keyword: ''
        },
        formInline: {
          name: '',
          desc: ''
        },
        formTemplate: {
          name: '',
          nodeCheckVal: [], //节点选中列表
        },
        nodesList: [], //节点列表
        nodeLoading: false,
        templateList: [],
        chooseType: 'node',
        indexOne: '',
        indexTwo: '',
        indexThree: '',
      }
    },
    watch: {

    },
    computed: {

    },
    destroyed() {
      window.onresize = null;
    },
    mounted() {
      this.$once('hook:beforeDestroy', function () {
        window.onresize = null;
      })
      this.onresize(); //监听搜索容器变化
      window.onresize = () => {
        this.onresize(); //监听搜索容器变化
      }
      this.getBrandList();
    },
    methods: {
      // 品牌列表
      getBrandList() {
        this.tableLoading = true;
        brandApi.getBrandList({
          page: this.page,
          num: this.num,
          keyword: this.formSearch.keyword
        }).then(res => {
          console.log(res, "品牌列表")
          this.tableLoading = false;
          if (res.code == 200) {
            this.tableData = res.data.list;
            this.total = res.data.max;
          } else {
            this.tableData = [];
            this.total = 0;
          }
        }).catch(() => {
          this.tableLoading = false;
        })
      },
      // 单页数据量修改
      handleSizeChange(e) {
        this.num = e;
        this.page = 1;
        this.getBrandList();
      },
      // 搜索
      onSearch(page) {
        this.page = page || 1;
        this.getBrandList();
      },
      handleCurrentChange(page) {
        this.page = page;
        this.getBrandList();
      },
      onresize() {
        let inter = '';
        clearTimeout(inter)
        inter = setTimeout(() => {
          if (!this.$refs.div) return;
          let height = this.$refs.div.$el.offsetHeight;
          height > 70 ? this.showOpne = true : this.showOpne = false;
          this.moreSearchShow = false;
        }, 1000);
      },
      moreSearch() {
        this.moreSearchShow = !this.moreSearchShow;
      },
      // 关闭添加弹窗
      handleClose() {
        if (this.dialogVisibleTemplate) {
          this.dialogVisibleTemplate = false;
          return;
        }
        this.dialogVisible = false;
      },
      // 
      submitFunc(formName) {
        let formInline = this.formInline;
        let templateList = this.templateList;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let template_list = [];
            console.log(templateList)
            templateList.forEach((item, index) => {
              let data_1 = {
                template_name: item.template_name,
                nodes: []
              }
              if (item.template_nodes) {
                item.template_nodes.forEach(child => {
                  let data_2 = {
                    nodes_name: child.node_name,
                    is_payment_review: child.is_payment_review,
                    criteria: []
                  };
                  if (child.children) {
                    child.children.forEach(i => {
                      data_2.criteria.push(i.node_name);
                    })
                  }
                  data_1.nodes.push(data_2);
                })
              }
              template_list.push(data_1);
            })
            if (formInline.id) {
              this.updBrand({
                name: formInline.name,
                desc: formInline.desc,
                brand_id: formInline.id,
                template_list
              })
              return;
            }
            this.addBrand({
              name: formInline.name,
              desc: formInline.desc,
              template_list
            });
          }
        });
      },
      // 添加品牌
      addBrand(obj) {
        brandApi.addBrand(obj).then(res => {
          console.log(res, "添加品牌")
          if (res.code == 200) {
            this.$message.success('添加成功');
            this.handleClose();
            this.onSearch();
          } else {
            this.$message.warning(res.message);
          }
        })
      },
      // 修改品牌
      handleEdit(data) {
        let formInline = this.formInline;
        this.currIndex = data.idnex;
        formInline.name = data.item.name;
        formInline.desc = data.item.desc;
        formInline.id = data.item.id;
        this.getBrandDetail({
          brand_id: data.item.id
        });
      },
      updBrand(data) {
        brandApi.updBrand(data).then(res => {
          console.log(res, "修改品牌")
          if (res.code == 200) {
            this.$message.success('修改成功');
            this.handleClose();
            this.onSearch(this.page);
          } else {
            this.$message.warning(res.message);
          }
        })
      },
      // 删除品牌
      handleDelete(data) {
        this.$confirm('此操作将删除该品牌, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          brandApi.delBrand({
            brand_id: data.id
          }).then(res => {
            console.log(res, "删除品牌")
            if (res.code == 200) {
              this.$message.success('删除成功');
              if (this.tableData.length == 1) {
                this.page = this.page > 1 ? this.page - 1 : this.page;
              }
              this.onSearch(this.page);
            } else {
              this.$message.warning(res.message);
            }
          }).catch(err => {
            this.$message.warning(err.message);
          })
        }).catch(() => {

        });
      },
      // 获取节点列表
      getNodesList(obj) {
        console.log(obj)
        this.nodeLoading = true;
        this.chooseType = obj.type;
        this.indexOne = obj.index;
        this.indexTwo = obj.childIndex || 0;
        this.indexThree = '';
        this.formTemplate.nodeCheckVal = [];
        nodesApi.getNodesList({
          page: 1,
          num: 9999,
          type: obj.type == 'node' ? 1 : 2
        }).then(res => {
          console.log(res, "节点列表")
          this.nodeLoading = false;
          if (res.code == 200) {
            this.nodesList = res.data.list;
            this.dialogVisibleTemplate = true;
            this.formTemplate.name = '';
            this.$nextTick(() => {
              this.$refs['ruleFormTemplate'].clearValidate();
            })
          }
        }).catch(err => {
          this.nodeLoading = false;
        })
      },
      // 模板添加
      submitTemplateFunc(formName) {
        let templateList = this.templateList;
        let formTemplate = this.formTemplate;
        let chooseType = this.chooseType;
        let indexOne = this.indexOne;
        let indexTwo = this.indexTwo;
        console.log(formTemplate)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (!formTemplate.nodeCheckVal.length) {
              this.$message.warning('请勾选验收节点');
              return;
            }
            // 添加标准
            if (chooseType != 'node') {
              formTemplate.nodeCheckVal.forEach(item => {
                templateList[indexOne].template_nodes[indexTwo].children.push({
                  is_payment_review: 2,
                  node_name: item,
                })
              })
              this.templateList = templateList;
              console.log(templateList)
              this.dialogVisibleTemplate = false;
              return;
            }
            // 模板内添加节点
            if (indexOne != undefined) {
              formTemplate.nodeCheckVal.forEach(item => {
                templateList[indexOne].template_nodes.push({
                  is_payment_review: 2,
                  node_name: item,
                  children: []
                })
              })
              this.templateList = templateList;
              this.dialogVisibleTemplate = false;
              return;
            }
            // 新增模板
            let obj = {
              template_name: formTemplate.name,
              template_nodes: []
            }
            formTemplate.nodeCheckVal.forEach(item => {
              obj.template_nodes.push({
                is_payment_review: 2,
                node_name: item,
                children: []
              })
            })
            templateList.push(obj);
            this.templateList = templateList;
            this.dialogVisibleTemplate = false;
          }
        });
      },
      // 模板文字修改
      openEdit(obj) {
        let {
          index,
          childIndex,
          k
        } = obj;
        let inputValue = '';
        let templateList = this.templateList;
        if (childIndex == undefined && k == undefined) {
          inputValue = templateList[index].template_name;
        } else if (childIndex != undefined && k == undefined) {
          inputValue = templateList[index].template_nodes[childIndex].node_name;
        } else {
          inputValue = templateList[index].template_nodes[childIndex].children[k].node_name;
        }
        this.$prompt('输入内容', '编辑', {
          inputValue,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^.+$/,
          inputErrorMessage: '内容不能为空'
        }).then(({
          value
        }) => {
          if (childIndex == undefined && k == undefined) {
            templateList[index].template_name = value;
          } else if (childIndex != undefined && k == undefined) {
            templateList[index].template_nodes[childIndex].node_name = value;
          } else {
            templateList[index].template_nodes[childIndex].children[k].node_name = value;
          }
          this.templateList = templateList;
        }).catch(() => {

        });
      },
      // 模板下的删除
      delFunc(obj) {
        let {
          index,
          childIndex,
          k
        } = obj;
        let templateList = this.templateList;
        console.log(templateList)
        if (childIndex == undefined && k == undefined) {
          templateList.splice(index, 1);
        } else if (childIndex != undefined && k == undefined) {
          templateList[index].template_nodes.splice(childIndex, 1);
        } else {
          templateList[index].template_nodes[childIndex].children.splice(k, 1);
        }
        this.templateList = templateList;
      },
      // 设值打款节点
      checkboxChange(obj) {
        let {
          index,
          childIndex
        } = obj;
        let templateList = this.templateList;
        templateList[index].template_nodes.forEach((item, k) => {
          if (k != childIndex) {
            item.is_payment_review = 2;
          }
        })
        templateList[index].template_nodes[childIndex].is_payment_review =
          templateList[index].template_nodes[childIndex].is_payment_review == 1 ? 2 : 1;
        this.templateList = templateList;
      },
      // 添加品牌
      addBrankFunc() {
        this.dialogVisible = true;
        this.formInline = {
          name: '',
          desc: ''
        }
        this.templateList = [];
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate();
        })
      },
      // 品牌详情
      getBrandDetail(data) {
        brandApi.getBrandDetail(data).then(res => {
          console.log(res, "品牌详情")
          if (res.code == 200) {
            this.templateList = res.data.template_list;
            this.dialogVisible = true;
          }
        })
      },
    }
  }

</script>

<style lang="scss" scoped>
  @import './index.scss';

</style>
